package com.bjpowernode.dataservice.service;

import com.bjpowernode.commons.constants.Status;
import com.bjpowernode.commons.exception.YLBException;
import com.bjpowernode.commons.service.AccountService;
import com.bjpowernode.commons.service.BidInfoService;
import com.bjpowernode.commons.service.ProductService;
import com.bjpowernode.dataservice.mapper.BidInfoMapper;
import com.bjpowernode.commons.model.BidInfo;
import com.bjpowernode.commons.model.Product;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

@DubboService
public class BidInfoServiceImpl implements BidInfoService {

    @Resource
    private BidInfoMapper bidInfoMapper;

    @Resource
    private AccountService accountService;

    @Resource
    private ProductService productService;

    public List<Map> top3() {
        return bidInfoMapper.top3();
    }

    @Transactional // 事务控制
    public void bid(Double money, Long prodId, Long userId) {
        // 账户余额扣减
        // where 账户余额 >= 投资金额
        if (accountService.updateBalance(userId, money) == 0) {
            throw new YLBException("账户余额不足！");
        }

        // 扣减产品剩余可投资金额
        if (productService.updateMoney(prodId, money) == 0) {
            throw new YLBException("产品余额不足！");
        }

        Date now = new Date();
        // 判断是否满标(剩余可投资金额小于最低投资金额)，如果满标，更新产品状态和满标时间
        Product product = productService.getById(prodId);
        if (product.getLeftProductMoney() < product.getBidMinLimit()) {
            productService.setFull(prodId, Status.PRODUCT.FULL, now);
        }

        // 添加投资记录
        BidInfo bidInfo = new BidInfo();
        bidInfo.setProdId(prodId);
        bidInfo.setUid(userId);
        bidInfo.setBidTime(now);
//        bidInfo.setBidStatus(1);
        bidInfo.setBidMoney(money);

        bidInfoMapper.insert(bidInfo);
    }

    public List getRecords(Long userId) {
        return bidInfoMapper.getRecords(userId);
    }

    public List<BidInfo> getBidInfoByProdId(Long id) {
        return bidInfoMapper.getBidInfoByProdId(id);
    }
}
